<template>
  <div class="page-container order-detail">
    <van-nav-bar
      title="订单详情"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      @click-left="onClickLeft"
    />

    <!-- 订单状态 -->
    <!-- <div class="status-card">
      <div class="status-info">
        <van-icon :name="orderStatusIcon" size="40" />
        <div class="status-text">
          <h3>{{ orderStatusText }}</h3>
          <p>{{ orderStatusDesc }}</p>
        </div>
      </div>
    </div> -->
    <div class="progress-bar">
      <van-steps :active="currentStep" active-color="#07c160">
        <van-step>填写订单</van-step>
        <van-step>待支付</van-step>
        <van-step>待服务</van-step>
        <van-step>已完成</van-step>
      </van-steps>
    </div>
        <!-- 订单状态 -->
    <div class="status-card">
      <div class="status-info">
        <van-icon :name="orderStatusIcon" size="40" />
        <div class="status-text">
          <h3 :style="{color:userStore.userInfo.ageGroup === 1 ? 'black': ''}">{{ orderStatusText }}</h3>
          <p :style="{color:userStore.userInfo.ageGroup === 1 ? 'black': '',fontSize:userStore.userInfo.ageGroup === 1 ? '18px' : ''}">{{ orderStatusDesc }}</p>
        </div>
      </div>
      <van-button v-if="orderInfo.orderStatus === 1 " type="primary"  size="large" @click="showPayOrder()" style="margin-top: 20px;" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}">立即支付</van-button>
      <van-button v-if="orderInfo.orderStatus === 2 " type="primary"  size="large" @click="ompleteOrder()" style="margin-top: 20px;" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}">完成服务</van-button>
      <van-button v-if="orderInfo.orderStatus === 3 " type="primary"  size="large" @click="goToEvaluate()" style="margin-top: 20px;" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}">去评价</van-button>
    </div>

    <!-- 医院信息 -->
    <div class="info-card">
      <div class="card-title">医院信息</div>
      <div class="hospital-info">
        <img v-if="orderInfo.image" :src="orderInfo.image" class="hospital-image" alt="医院图片" />
        <img v-else src="../../assets/images/hospital.png" class="hospital-image" alt="医院图片" />
        <div class="hospital-details">
          <h4 :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}">{{ orderInfo.hospitalName }}</h4>
          <div class="hospital-meta">
            <span class="hospital-grade">{{ orderInfo.grade }}</span>
            <span class="hospital-type">{{ orderInfo.type }}</span>
          </div>
          <h4 style="color: #07C160;">{{ orderInfo.serviceName }}</h4>
        </div>
      </div>
    </div>

    <!-- 就诊信息 -->
    <div class="info-card">
      <div class="card-title">就诊信息</div>
      <van-cell-group inset :border="false">
        <van-cell title="服务对象" :value="orderInfo.serviceObject"  :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell title="服务对象电话" :value="orderInfo.serviceObjectPhone" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell v-if="orderInfo.serviceName === '代跑取药'" title="诊断结果" :value="orderInfo.result" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell v-if="orderInfo.serviceName === '代跑取药'" title="取药码" :value="orderInfo.deliveryCode" />
        <van-cell v-if="orderInfo.serviceName === '送取就医结果' || orderInfo.serviceName === '代跑取药'" title="身份证号" :value="orderInfo.idNumber" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell v-if="orderInfo.serviceName === '代跑取药'" title="医保卡号" :value="orderInfo.medicalNumber" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell v-if="orderInfo.serviceName === '送取就医结果'" title="就诊卡号" :value="orderInfo.medicalCardNumber" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell v-if="orderInfo.serviceName !== '诊前约号'" :title="orderInfo.serviceName ==='就医陪诊' ? '接送地址' : orderInfo.serviceName ==='上门陪护' ? '陪护地址' : '接收地址'" :value="orderInfo.address" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell v-if="orderInfo.serviceName === '上门陪护'" title="陪护类型" :value="orderInfo.escortType" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
      </van-cell-group>
    </div>


    <!-- 就诊时间 -->
    <div class="info-card" v-if="orderInfo.serviceName === '就医陪诊' || orderInfo.serviceName === '诊前约号'" >
      <div class="card-title">就诊时间</div>
      <van-cell-group inset :border="false">
        <van-cell v-if="orderInfo.serviceName === '就医陪诊' || orderInfo.serviceName === '诊前约号'" title="就诊日期" :value="orderInfo.visitDate" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell v-if="orderInfo.serviceName === '就医陪诊' || orderInfo.serviceName === '诊前约号'" title="就诊时间" :value="orderInfo.visitTime" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
      </van-cell-group>
    </div>


    <!-- 就诊时间 -->
    <div class="info-card">
      <div class="card-title">服务专员</div>
      <van-cell-group inset :border="false">
        <van-cell title="服务专员" :value="orderInfo.serviceStaffName" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell title="专员年龄" :value="orderInfo.servicePersonneAge" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell title="联系电话" :value="orderInfo.serviceStaffPhone" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
      </van-cell-group>
    </div>

    <!-- 订单信息 -->
    <div class="info-card">
      <div class="card-title">订单信息</div>
      <van-cell-group inset :border="false">
        <van-cell title="订单编号" :value="orderInfo.orderNo" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell title="下单时间" :value="orderInfo.createTime" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell title="支付方式" :value="orderInfo.payMethod" v-if="orderInfo.payMethod" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell title="支付时间" :value="orderInfo.payTime" v-if="orderInfo.payTime" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
        <van-cell title="订单备注" :value="orderInfo.remark ? orderInfo.remark : '暂无'" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"/>
      </van-cell-group>
    </div>

    <!-- 订单金额 -->
    <div class="info-card">
      <div class="card-title">订单金额</div>
      <van-cell-group inset :border="false">
        <van-cell title="订单金额" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}">
          <template #value>
            <span class="price" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '35px' : ''}">￥{{ orderInfo.orderAmount }}</span>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 订单金额 -->
    <div class="info-card" v-if="orderInfo.serviceName === '诊前约号'">
      <div class="card-title">就诊流程</div>
      <div class="process-list">
        <div class="process-item" v-for="(item, index) in processList" :key="index">
          <div class="process-step">
            <span class="step-number">{{ index + 1 }}</span>
          </div>
          <div class="process-content">
            <h5>{{ item.title }}</h5>
            <p>{{ item.desc }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <!-- <div class="bottom-bar" v-if="orderInfo.status === 'unpaid'">
      <van-button plain type="default" @click="cancelOrder">取消订单</van-button>
      <van-button type="primary" @click="payOrder">立即支付</van-button>
    </div> -->

        <!-- 支付密码弹框 -->
        <van-popup v-model:show="showPayPassowrd" position="bottom">
        <div class="pay-title">请输入支付密码</div>
        <div class="pay-title-tip">向{{orderInfo.hospitalName}}转账</div>
        <h1 style="text-align: center;">¥{{ orderInfo.orderAmount }}</h1>
            <!-- 密码输入框 -->
          <van-password-input
          :value="payPassword"
            :focused="showKeyboard"
          style="margin-bottom: 500px;"
          @focus="showKeyboard = true"
        />
          <!-- 数字键盘 -->
        <van-number-keyboard
          v-model="payPassword"
        :show="showKeyboard"
          @blur="showKeyboard = false"
        />
        </van-popup>


        <van-dialog v-model:show="showEvaluate"  title="评价" @confirm="onSubmitEvaluate">
        <van-cell-group inset>
          <van-field
            v-model="evaluate"
            rows="2"
            autosize
            label="评价"
            type="textarea"
            maxlength="100"
            placeholder="请输入评价"
            show-word-limit
        />
        </van-cell-group>
        </van-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted,watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showConfirmDialog, showToast } from 'vant'
import { parseBusinessContent, processHospitalImage } from '@/utils/utils'
import { carouselApi, hospitalApi,orderApi } from '@/api'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const router = useRouter()
const route = useRoute()

const processList = [
  {
    title: '按时到达',
    desc: '按照预约时间提前到达医院，避免迟到影响就诊'
  },
  {
    title: '签到取号',
    desc: '在指定地点签到并领取就诊号码'
  },
  {
    title: '候诊就诊',
    desc: '进入诊室后向医生详细在候诊区等待叫号，进入诊室向医生陈述病情描述症状'
  },
  {
    title: '检查缴费',
    desc: '如需进行检查，医生开具检查单后缴费并前往相应科室检查。'
  },
  {
    title: '领取结果复诊',
    desc: '拿到检查结果后返回诊室复诊。'
  },
  {
    title: '取药离院',
    desc: '医生开具处方后，缴费取药，完成就诊离院。'
  }
]

const orderStatusText = computed(() => {
  const textMap = {
    1: '待支付',
    2: '待服务',
    3: '已完成',
    4: '已取消'
  }
  return textMap[orderInfo.value.orderStatus] || '未知状态'
})

const orderStatusDesc = computed(() => {
  const descMap = {
    1: '请在30分钟内完成支付',
    2: '正在安排服务专员为您服务，请保持电话畅通，稍后将有服务专员与您联系',
    3: '服务已完成',
    4: '服务已取消'
  }
  return descMap[orderInfo.value.orderStatus] || ''
})
const orderStatusIcon = computed(() => {
  const textMap = {
    1: 'cash-back-record-o',
    2: 'phone-o',
    3: 'passed',
    4: 'close'
  }
  return textMap[orderInfo.value.orderStatus] || ''
})

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 取消订单
const cancelOrder = async () => {
  try {
    await showConfirmDialog({
      title: '取消订单',
      message: '确定要取消该订单吗？'
    })
    // TODO: 调用取消订单接口
    showToast('取消成功')
    router.back()
  } catch {
    // 用户取消操作
  }
}


//步骤条状态
const currentStep = ref(1)
// 订单信息
const orderInfo = ref({
  id: '1',
  orderNo: '202401010001',
  status: 'unpaid', // unpaid-待支付, unserved-待服务, completed-已完成
  hospitalName: '某某医院',
  departmentName: '内科',
  patientName: '张三',
  visitDate: '2024-01-01',
  visitTime: '09:00',
  phone: '13800138000',
  createTime: '2024-01-01 08:00:00',
  price: '200.00',
  image:'',
  grade:'',//医院等级
  type:''//医院类型
})

// 获取订单详情
const getOrderDetail = async () => {
  const orderData = route.query.orderData
  const data = {}
  //此处evaluateData用于存储不同业务字段信息，用于评价
  evaluateData.value = JSON.parse(decodeURIComponent(orderData)).businessContent
  data.value = JSON.parse(decodeURIComponent(orderData))
  orderInfo.value = parseBusinessContent(data).value
  const res = await hospitalApi.getHospitalList()
  if(res.code === 200){
    const targetHospital = res.data.records.find(hospital => hospital.id === orderInfo.value.hospitalId);
  if (targetHospital) {
    orderInfo.value.image = targetHospital.image
    orderInfo.value.grade = targetHospital.grade
    orderInfo.value.type = targetHospital.type
    orderInfo.value = await processHospitalImage(orderInfo.value)
  }else{
    showToast('获取医院图片失败')
  }
  }else {
    showToast('获取医院图片失败')
  }
  currentStep.value = orderInfo.value.orderStatus
  console.log('订单信息',orderInfo.value)
}

// 页面加载时获取订单详情


//订单支付
const showPayPassowrd = ref(false)
const payPassword = ref('')
const showKeyboard = ref(true)

const showPayOrder = () => {
  showPayPassowrd.value = true
}

const payOrder = async () => {
  try {
    let params = {
      orderId: Number(orderInfo.value.id),
      payPassword: payPassword.value
    }
    const res = await orderApi.payOrder(params) 
    if (res.code === 200) {
      // 清理支付相关状态
      payPassword.value = ''
      showPayPassowrd.value = false
      showToast('支付成功')
      router.push('/order')
    } else {
      payPassword.value = ''
      showPayPassowrd.value = false
      showToast(`支付失败,${res.message}`)
    }
  } catch (error) {
    payPassword.value = ''
    showPayPassowrd.value = false
    console.log('支付失败', error)
    showToast(`支付失败,${res.error}`)
  }
}
watch(payPassword, (newValue) => {
  if (newValue && newValue.length === 6) {
    console.log('payPassword', newValue)
    payOrder()
  }
});

//完成服务
const ompleteOrder = async () => {
  try {
    await showConfirmDialog({
      title: '完成服务',
      message: '确定该服务已完成？'
    })
    // TODO: 调用取消订单接口
    let params = {
      id:orderInfo.value.id,
      status:3
    }
    const res = await orderApi.updateOrderStatus(params)
    if(res.code === 200){
      showToast('订单服务完成')
      router.push('/order')
    }else {
      showToast('订单服务完成异常')
    }
  } catch (error) {
    console.log('订单服务完成异常')
  }
}



//去评价
const evaluate = ref('')
const evaluateData = ref('')
const showEvaluate = ref(false)
const goToEvaluate = () =>{
  console.log('orderInfo',orderInfo.value)
  if(orderInfo.value.evaluate){
    showToast('您已参评，请勿重复评价')
        return
  }
  showEvaluate.value = true
}
const onSubmitEvaluate = async () => {
  if(!evaluate.value){
    return
  }
  evaluate.value = evaluateData.value + ',' + 'evaluate:' + evaluate.value
  console.log('evaluate',evaluate.value)
  try{
  let params = {
    id:orderInfo.value.id,
    businessContent:evaluate.value
  }
  const res = await orderApi.updateOrder(params)
  if(res.code === 200){
    showToast('感谢您的评价')
      evaluate.value = ''
      evaluateData.value = ''
      router.push('/order')
  }
}catch(error){
  showToast(error)
}
}



onMounted( async() => {
  getOrderDetail()
})
</script>

<style lang="scss" scoped>
.order-detail {
  padding-bottom: 80px;

  .status-card {
    padding: 24px 16px;
    margin-bottom: 12px;
    // background: linear-gradient(to right, #f1f1f1, #e5e5e5);
    background: #5ce59e;
    color: #fff;

    .status-info {
      display: flex;
      align-items: center;
      gap: 16px;

      .status-text {
        h3 {
          margin: 0 0 4px;
          font-size: 20px;
          font-weight: 500;
        }

        p {
          margin: 0;
          font-size: 14px;
          opacity: 0.8;
        }
      }
    }
  }

  .info-card {
    margin-bottom: 12px;

    .card-title {
      padding: 0 16px;
      margin-bottom: 12px;
      font-size: 16px;
      font-weight: 500;
      color: var(--text-color);
    }

    .hospital-info {
      padding: 16px;
      margin: 0 16px;
      background: #fff;
      border-radius: 8px;
      display: flex;
      align-items: center;

      .hospital-image {
        width: 48px; /* 设置医院图片的宽度 */
        height: 48px; /* 设置医院图片的高度 */
        border-radius: 8px; /* 圆角 */
        margin-right: 12px; /* 图片与医院名称之间的间距 */
        object-fit: cover; /* 保持图片比例 */
      }

      .hospital-details {
        flex: 1;

        h4 {
          margin: 0;
          font-size: 16px;
          color: var(--text-color);
        }

        .hospital-meta {
          display: flex;
          gap: 8px; /* 间距 */
          font-size: 12px; /* 字体大小 */
          color: var(--text-color-secondary);

          .hospital-grade{
            background: rgba(7, 193, 96, 0.1); /* 背景色 */
            padding: 4px 8px; /* 内边距 */
            border-radius: 4px; /* 圆角 */
            color: #07c160
          }
          .hospital-type {
            background: rgba(59, 130, 246, 0.1); /* 背景色 */
            padding: 4px 8px; /* 内边距 */
            border-radius: 4px; /* 圆角 */
            color: #3b82f6
          }
        }
      }
    }

    .price {
      color: #ee0a24;
      font-weight: 500;
    }
  }

  .bottom-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    gap: 12px;
    padding: 8px 16px;
    background: #fff;
    border-top: 1px solid var(--border-color);

    .van-button {
      flex: 1;
    }
  }
}
  .progress-bar {
    padding: 20px 16px;
    background: #fff;
    // margin-bottom: 12px;
  }
  .process-list {
      padding: 16px;
      margin: 0 16px;
      background: #fff;
      border-radius: 8px;

      .process-item {
        display: flex;
        gap: 16px;
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        .process-step {
          .step-number {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            background: var(--primary-color);
            color: #fff;
            border-radius: 50%;
            font-size: 14px;
          }
        }

        .process-content {
          flex: 1;

          h5 {
            margin: 0 0 4px;
            font-size: 16px;
            color: var(--text-color);
          }

          p {
            margin: 0;
            font-size: 14px;
            color: var(--text-color-secondary);
          }
        }
      }
    }
    .pay-title{
    margin-left: 115px;
    margin-top: 20px;
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 800
    } 
    .pay-title-tip{
    text-align: center;
    margin-top: 20px;
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 800
  }
</style> 